import { Select2Page } from "../../../common/serve-request.js";
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import ReceivepigApi from '../../../common/api/cbs/receivepig.api.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import { locationService } from '../../../common/locationService.js';

(function (window, document, $) {
    let _vm, savetype, getEntryInfo = []
    $(function () {
        _vm = new Vue({
            el: "#saleordersentry-form",
            data() {
                return {
                    entries: [{
                        "seq": "",
                        "carNo": "",
                        "driverId": "",
                        "driverName": "",
                        "tareWeight": "",
                        "grossWeight": "",
                        "netWeight": "",
                        "farmerId": "",
                        "farmerName": "",
                        "count": "",
                        "buyLossCount": "",
                        "breedBatchId": "",
                        "breedBatchName": "",
                        "pigBreed": "",
                        "netWeightStr": "",
                        "uploadCount": 0,
                        "attachesStr": [],
                    }],
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                if (params.isEdit == 'true') {
                    document.title = '接苗单分录 - 编辑'
                }
            },
            methods: {
                submit() {
                    let { carNo, driverName, tareWeight, grossWeight, farmerId, count, buyLossCount, breedBatchId, pigBreed
                    } = _vm.entries[0]
                    if (!Utils.IsNotNull(carNo)) {
                        return $.toptip(`请输入车牌号!`, 'warning');
                    }
                    if (!Utils.IsNotNull(driverName)) {
                        return $.toptip(`请输入司机姓名!`, 'warning');
                    }
                    if (!Utils.IsNotNull(count)) {
                        return $.toptip(`请输入数量!`, 'warning');
                    }
                    if (!Utils.IsNotNull(grossWeight)) {
                        return $.toptip(`请输入毛重!`, 'warning');
                    }
                    if (!Utils.IsNotNull(tareWeight)) {
                        return $.toptip(`请输入皮重!`, 'warning');
                    }
                    if (!Utils.IsNotNull(pigBreed)) {
                        return $.toptip(`请选择猪只品种!`, 'warning');
                    }
                    if (buyLossCount === '' || buyLossCount === 'undefined') {
                        return $.toptip(`请输入买方损耗数量!`, 'warning');
                    }
                    if (!Utils.IsNotNull(farmerId)) {
                        return $.toptip(`请选择养户!`, 'warning');
                    }
                    if (!Utils.IsNotNull(breedBatchId)) {
                        return $.toptip(`请选择养殖批次!`, 'warning');
                    }
                    if (!(/(^[1-9]\d*$)/.test(count))) {
                        return $.toptip(`数量必须为大于0的整数!`, 'warning');
                    }
                    //车牌
                    const LICENSE_PLATE = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/;
                    if (Utils.IsNotNull(carNo) && !(LICENSE_PLATE.test(carNo))) return $.toptip(`请输入正确的车牌号`, 'warning')
                    var reg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
                    if (!(reg.test(grossWeight))) return $.toptip(`毛重必须大于0并且只能保留两位小数`, 'warning')
                    if (!(reg.test(tareWeight))) return $.toptip(`皮重必须大于0并且只能保留两位小数`, 'warning')
                    if (!(/^[1-9]\d*$|^0$/.test(buyLossCount))) {
                        return $.toptip(`买方损耗数量必须为大于等于0的整数!`, 'warning');
                    }
                    savetips({ ..._vm.entries[0] })
                }
            }
        });
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _initCommand();
    });

    // 初始化数据
    const _initCommand = async () => {
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo")) || []
        let isEdit = JSON.parse(getUrlKey('isEdit'))
        let seq = getUrlKey('index')
        let sdit = getUrlKey('sdit')
        // 编辑时赋值
        if (isEdit) {
            let datas = getEntryInfo.find(item => item.seq == seq)
            const propertiesToCopy = [
                "carNo", "driverId", "driverName", "tareWeight", "grossWeight", "netWeight", "farmerId", "farmerName", "count", "buyLossCount", "breedBatchId", "breedBatchName", "pigBreed", "netWeightStr"
            ];
            propertiesToCopy.reduce((obj, prop) => {
                _vm.entries[0][prop] = datas[prop];
            }, {});
            _vm.entries[0].attachesStr = []
            _vm.entries[0].netWeightStr = Utils.toThousands(_vm.entries[0].netWeight)
            // 附件
            let editImage = []
            if (Utils.IsNotNull(datas.attachesStr)) {
                datas.attachesStr.forEach(item => {
                    editImage.push({
                        "imageId": item.imageId
                    })
                })
                _images(editImage)
                _vm.entries[0].uploadCount = datas.attachesStr.length
            }
            if (Utils.IsNotNull(datas.attaches) && Utils.IsNotNull(isEdit)) {
                datas.attaches.split(',').forEach(item => {
                    editImage.push({
                        "imageId": item
                    })
                })
                _images(editImage)
                _vm.uploadCount = datas.attaches.split(',').length
            }

        }
        uploadInit()

        // 初始化 品种
        let type = await requestDict(DictionaryType.PIG_VARIETIES)
        let remedyDate = type.data;
        $('#breed').empty().select2({
            placeholder: '请选择猪只品种...', //默认文字提示
            language: "zh-CN", //汉化
            allowClear: true, //允许清空
            data: remedyDate.map(item => {
                return {
                    id: item.value,
                    text: item.displayName,
                }
            }),
        });
        let pigDefault = remedyDate.filter(item => {
            return item.isDefault == true
        })
        if (!isEdit) {
            $(`#breed`).val(pigDefault[0]?.value).trigger("change")
            _vm.entries[0].pigBreed = pigDefault[0]?.value
        }
        else {
            $(`#breed`).val(_vm.entries[0].pigBreed).trigger("change")
        }
        //选择品种
        $('#breed').on("select2:select", function () {
            _vm.entries[0].pigBreed = $('#breed').select2('data')[0]?.id
        });
        // 初始化 养户
        Select2Page($(`#fosterfarmers`), `${Utils.CurDomain.CBSUrl}/fosterfarmers/by/q`, (params) => {
            if (Utils.IsNotNull(sdit)) {
                return ({
                    OrgId: sdit,
                    SearchInfo: params.term,
                    pageSize: 10,
                    pageIndex: (params.page || 1) - 1
                });
            } else {
                return ({
                    SearchInfo: params.term,
                    pageSize: 10,
                    pageIndex: (params.page || 1) - 1
                });
            }

        }, "GET", {
            allowClear: true,//允许清空
            placeholder: '请选择养户...', //默认文字提示
            templateResult: function (res) {
                return `${res.name}(${res.phone})`;
            }
        });
        $(`#fosterfarmers`).setSelectValue(_vm.entries[0].farmerId, _vm.entries[0].farmerName);
        // 选择养户
        $(`#fosterfarmers`).on('select2:select', async function () {
            await _select2($(this).val(), true);
            _vm.entries[0].farmerId = $('#fosterfarmers').select2('data')[0]?.id
            _vm.entries[0].farmerName = $('#fosterfarmers').select2('data')[0]?.name
            $(`#breedBatch`).setSelectValue()
        }).on('select2:clear', function () {
            $(`#breedBatch`).empty()
            _vm.entries[0].farmerId = ''
            _vm.entries[0].farmerName = ''
        });
        // 初始化 养殖批次
        $(`#breedBatch`).empty().select2({
            placeholder: `请选择养殖批次...`, //默认文字提示
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            data: []
        });
        if (Utils.IsNotNull(_vm.entries[0].farmerId)) {
            _select2(_vm.entries[0].farmerId, false)
        }
        // 选择养殖批次
        $(`#breedBatch`).on('select2:select', function () {
            _vm.entries[0].breedBatchId = $('#breedBatch').select2('data')[0]?.id
            _vm.entries[0].breedBatchName = $('#breedBatch').select2('data')[0]?.text
        }).on('select2:clear', function () {
            _vm.entries[0].breedBatchId = ''
            _vm.entries[0].breedBatchName = ''
        });

        $('#grossWeight,#tareWeight').on('change', function () {
            if (Utils.IsNotNull(_vm.entries[0].grossWeight) && Utils.IsNotNull(_vm.entries[0].tareWeight)) {
                _vm.entries[0].netWeight = _vm.entries[0].grossWeight - _vm.entries[0].tareWeight
                _vm.entries[0].netWeightStr = Utils.toThousands(_vm.entries[0].grossWeight - _vm.entries[0].tareWeight, 2)
            }
        })

        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../receivepig/addreceivepig.html?v=${Utils.GetTime()}`;
        });
    }
    // 初始化 养殖批次
    const _select2 = async (farmId, json) => {
        if (!Utils.IsNotNull(farmId) && !Utils.IsNotNull(json)) {
            $(`#breedBatch`).empty().select2({});
            return false;
        }
        let _batch = await ReceivepigApi.getFosterBatch(farmId);
        $(`#breedBatch`).empty().select2({
            placeholder: `请选择养殖批次...`, //默认文字提示
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            data: _batch.map(item => {
                return {
                    id: item.breedBatchId,
                    text: item.breedBatchName
                }
            })
        });
        if (json == false) {
            $(`#breedBatch`).setSelectValue(_vm.entries[0].breedBatchId, _vm.entries[0].breedBatchName);
        }
    }
    // 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                if (!isMobile() && files.length > 0) {
                    $.toptip('请使用手机拍照上传！', 'warning');
                    return false;
                }
                if (["image/jpg", "image/jpeg", "image/png"].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                $.showLoading('上传中..');
                _vm.entries[0].uploadCount = ++_vm.entries[0].uploadCount;
                if (_vm.entries[0].uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: async function () {
                const file = this;
                let suffix = this.name.split('.').pop().toLowerCase(); //截取附件后缀
                let name = this.name.slice(0, 11 - (suffix.length) - 1); //计算截取文件的11位字符
                let newName = name + '.' + suffix
                let file1 = publicFileDraw(newName, _vm);
                // 在这里添加日期和地点水印
                const currentDate = moment(new Date()).format('YYYY-MM-DD')
                const currentTime = moment(new Date()).format('HH:mm:ss')
                const locationWatermark = $('#addressInfo').text()
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const image = new Image();
                image.src = window.URL.createObjectURL(file);

                if (!Utils.IsNotNull(locationWatermark)) {
                    $.toptip('定位失败!', 'warning');
                    $.hideLoading();
                    $('#uploaderFiles').last().empty()
                    return
                }
                image.onload = function () {
                    canvas.width = image.width;
                    canvas.height = image.height;
                    // 在canvas上绘制原始图片
                    context.drawImage(image, 0, 0);

                    // 添加水印，支持换行
                    const watermarkText = currentDate + ' ' + currentTime + '\n' + locationWatermark;
                    context.font = '700 ' + 80 + 'px Arial';
                    context.fillStyle = 'white';

                    // 在指定位置绘制文本
                    const x = 10;
                    const y = image.height - 160;
                    drawWrappedText(context, watermarkText, x, y, 200, 130);  // 调用自定义函数

                    // 将canvas转为Blob
                    canvas.toBlob(function (blob) {
                        const formData = new FormData();
                        formData.append('apiobjfile', blob, file1);
                        _uploadFileDraw(formData, file, _vm);
                    }, file.type || 'image/png');  // 使用原始图片的类型或默认为PNG
                }
            }
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            // _vm.attaches = _vm.attaches.filter(item => item.id != _id);
                            // _vm.uploadCount = --_vm.uploadCount;
                            _vm.entries[0].attachesStr = _vm.entries[0].attachesStr.filter(item => item.id != _id);
                            _vm.entries[0].uploadCount = --_vm.entries[0].uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.entries[0].uploadCount == 3) {
                                $(".weui-uploader__input-box").hide();
                            } else {
                                $(".weui-uploader__input-box").show();
                            }
                        },
                        onCancel: function () {
                        }
                    });
                }
            });
        });
    }
    // 自定义函数，用于在Canvas上绘制换行的文本
    function drawWrappedText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split('\n');
        var line = '';
        var yOffset = 0;

        for (var i = 0; i < words.length; i++) {
            var word = words[i];
            var testLine = line + word + ' ';
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;

            if (testWidth > maxWidth && i > 0) {
                context.fillText(line, x, y + yOffset);
                line = word + ' ';
                yOffset += lineHeight;
            } else {
                line = testLine;
            }
        }

        context.fillText(line, x, y + yOffset);
    }
    function isMobile() {
        return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
    }
    // 附件上传
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile).then(async res => {
            if (res.isSucceed) {
                let imageurl = await requestFilePath(res.data)
                let _list = _vm.entries[0].attachesStr;
                _list.push({
                    id: $("#uploaderFiles li").length,
                    imageId: res.data,
                    url: imageurl.data,
                });
                _vm.entries[0].attachesStr = _list;
                $("#uploaderFiles li").each(function (i) {
                    $(this).attr('data-id', _vm.entries[0].attachesStr[i].id);
                    $(this).attr('data-image-id', _vm.entries[0].attachesStr[i].imageId);
                    $(this).attr('data-url', _vm.entries[0].attachesStr[i].url);
                    $(this).css({ 'background-image': `url(${_vm.entries[0].attachesStr[i].url})` });
                });
                $('.weui-uploader__file-content').hide();
                $('.weui-uploader__file').removeClass('weui-uploader__file_status');
            }
        }).catch(res => {
            $("#uploaderFiles li").eq($("#uploaderFiles li").length - 1).remove();
            _vm.entries[0].uploadCount = --_vm.entries[0].uploadCount;
            $.toptip(res.msg, 'error');
        }).finally(_ => {
            $.hideLoading();
            $.closeModal();
        });
    }
    // 编辑回显
    const _images = async (file) => {
        let _imag = file;
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i].imageId).then(_res => {
                    _vm.entries[0].attachesStr.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i].imageId,
                    });
                    if (_res.isSucceed) {
                        let _li;
                        _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i].imageId}" style="background-image: url(${_res.data}) "></li>`;
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $(".weui-uploader__input-box").hide();
            }
            _vm.entries[0].uploadCount = _sun;
        }
    }
    // 保存提示
    const savetips = (data) => {
        let saveEntry
        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
            savetype = '修改'
            saveEntry = getUrlKey("operaEntryId")
        }
        else {
            savetype = '保存'
            saveEntry = getUrlKey('nextEntryId')
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
    				<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
    					<div>是否确认${savetype}该分录？</div>
    				</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        let seq = parseInt(getUrlKey('index'))
                        let isEdit = JSON.parse(getUrlKey('isEdit'))
                        // 新增
                        if (Utils.IsNotNull(getEntryInfo) && isEdit == false) {
                            getEntryInfo.push(data)
                        } else if (Utils.IsNotNull(getEntryInfo) && isEdit) {
                            // 编辑
                            getEntryInfo[seq] = data
                        } else {
                            getEntryInfo.push(data)
                        }
                        getEntryInfo.map((item, index) => {
                            item.seq = index
                        })
                        // 存入SessionStorage
                        JSON.stringify(Utils.SetSessionStorage("getEntryInfo", getEntryInfo))
                        location.href = `./addreceivepig.html?v=${Utils.GetTime()}`;
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

})(window, document, jQuery)